package a07_二叉树;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <p>
 * a03_层序遍历01_二叉树的层序遍历
 * 需要注意的是，只有当左右孩子都为空的时候，才说明遍历的最低点了。如果其中一个孩子为空则不是最低点
 * </p>
 *
 * @author flyduck
 * @since 2024-08-20
 */
public class a05_层序遍历09_二叉树的最小深度 {

    public static void main(String[] args) {
//        TreeNode root = new TreeNode(
//                6,
//                new TreeNode(4,new TreeNode(1),new TreeNode(3)),
//                new TreeNode(7,new TreeNode(5),new TreeNode(8)));
        TreeNode root = new TreeNode(
                6,
                new TreeNode(4),
                new TreeNode(7,new TreeNode(5),new TreeNode(8)));
        int i = minDepth(root);
        System.out.println(i);
    }

    public static int minDepth(TreeNode root) {
        int minDepth = 0;
        if (root == null) {
            return minDepth;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int popSize = queue.size();
            while (popSize > 0) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
                if(poll.left == null && poll.right == null){
                    minDepth++;
                    return minDepth;
                }
                popSize--;
            }
            minDepth++;
        }
        return minDepth;

    }


}

